package isoft.controller;

import isoft.model.*;

import java.util.List;
import java.util.Scanner;

public class GoodsController {
    private ProductDatabase productDatabase;
    private User currentUser;
    private Scanner scanner;
    private static final String ADMIN_KEY = "admin123";  // 固定的管理员钥匙密码

    public GoodsController() {
        this.productDatabase = new ProductDatabase();
        this.scanner = new Scanner(System.in);
    }

    public void startSystem() {
        while (true) {
            System.out.println("欢迎使用收银台管理系统");
            System.out.println("1. 管理员");
            System.out.println("2. 用户");
            System.out.println("3. 退出");
            System.out.print("请选择操作: ");
            int choice = scanner.nextInt();
            scanner.nextLine();  // 清除输入缓冲区中的换行符

            switch (choice) {
                case 1:
                    adminLogin();
                    break;
                case 2:
                    userLoginOrRegister();
                    break;
                case 3:
                    System.out.println("退出系统，感谢使用！");
                    return;
                default:
                    System.out.println("无效的选择，请重新输入。");
            }
        }
    }

    private void adminLogin() {
        System.out.print("请输入管理员密钥密码: ");
        String adminKey = scanner.nextLine();
        if (ADMIN_KEY.equals(adminKey)) {
            currentUser = new Admin("admin", "admin123");  // Admin用户需要有管理员账户
            adminMenu();
        } else {
            System.out.println("密钥密码错误，登录失败。");
        }
    }

    private void userLoginOrRegister() {
        while (true) {
            System.out.println("1. 注册");
            System.out.println("2. 登录");
            System.out.println("3. 返回主菜单");
            System.out.print("请选择操作: ");
            int choice = scanner.nextInt();
            scanner.nextLine();  // 清除输入缓冲区中的换行符

            switch (choice) {
                case 1:
                    registerUser();
                    break;
                case 2:
                    loginUser();
                    break;
                case 3:
                    return;  // 返回主菜单
                default:
                    System.out.println("无效的选择，请重新输入。");
            }
        }
    }

    private void registerUser() {
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();

        User newUser = new User(username, password, "USER");
        productDatabase.addUser(newUser);
        System.out.println("注册成功！");
        loginUser();  // 注册成功后直接登录
    }

    private void loginUser() {
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();

        User user = productDatabase.findUserByUsername(username);
        if (user != null && user.getPassword().equals(password)) {
            this.currentUser = user;
            System.out.println("登录成功，欢迎 " + username + "！");
            userMenu();
        } else {
            System.out.println("用户名或密码错误。");
        }
    }

    private void adminMenu() {
        while (true) {
            System.out.println("\t\t 管理员菜单");
            System.out.println("----------------");
            System.out.println("1. 添加商品");
            System.out.println("2. 修改商品信息");
            System.out.println("3. 删除商品");
            System.out.println("4. 查询所有订单");
            System.out.println("5. 修改用户信息");
            System.out.println("6. 退出");
            System.out.println("----------------");
            System.out.print("请选择(1|2|3|4|5|6): ");
            int choice = scanner.nextInt();
            scanner.nextLine();  // 清除输入缓冲区中的换行符

            switch (choice) {
                case 1:
                    addProduct();
                    break;
                case 2:
                    updateProduct();
                    break;
                case 3:
                    deleteProduct();
                    break;
                case 4:
                    viewAllOrders();
                    break;
                case 5:
                    updateUser();
                    break;
                case 6:
                    return;  // 返回主菜单
                default:
                    System.out.println("无效的选择，请重新输入。");
            }
        }
    }

    private void userMenu() {
        while (true) {
            System.out.println("\t\t 用户菜单");
            System.out.println("----------------");
            System.out.println("1. 查询商品信息");
            System.out.println("2. 查看我的订单");
            System.out.println("3. 退出");
            System.out.println("----------------");
            System.out.print("请选择(1|2|3): ");
            int choice = scanner.nextInt();
            scanner.nextLine();  // 清除输入缓冲区中的换行符

            switch (choice) {
                case 1:
                    queryProduct();
                    break;
                case 2:
                    viewMyOrders();
                    break;
                case 3:
                    return;  // 返回主菜单
                default:
                    System.out.println("无效的选择，请重新输入。");
            }
        }
    }

    private void addProduct() {
        while (true) {
            System.out.print("请输入商品ID: ");
            String id = scanner.nextLine();
            System.out.print("请输入商品名称: ");
            String name = scanner.nextLine();
            System.out.print("请输入商品价格: ");
            double price = scanner.nextDouble();
            System.out.print("请输入商品库存: ");
            int stock = scanner.nextInt();
            scanner.nextLine();  // 清除输入缓冲区中的换行符

            Product product = new Product(id, name, price, stock);
            productDatabase.addProduct(product);
            System.out.println("商品添加成功！");

            System.out.println("1. 继续添加商品");
            System.out.println("2. 返回管理员菜单");
            System.out.print("请选择操作: ");
            int choice = scanner.nextInt();
            scanner.nextLine();  // 清除输入缓冲区中的换行符

            if (choice == 2) {
                return;
            }
        }
    }

    private void updateProduct() {
        System.out.print("请输入要修改的商品ID: ");
        String id = scanner.nextLine();
        Product product = productDatabase.findProductById(id);
        if (product != null) {
            System.out.print("请输入新的商品名称(当前: " + product.getName() + "): ");
            String name = scanner.nextLine();
            System.out.print("请输入新的商品价格(当前: " + product.getPrice() + "): ");
            double price = scanner.nextDouble();
            System.out.print("请输入新的商品库存(当前: " + product.getStock() + "): ");
            int stock = scanner.nextInt();
            scanner.nextLine();  // 清除输入缓冲区中的换行符

            product.setName(name);
            product.setPrice(price);
            product.setStock(stock);
            productDatabase.updateProduct(product);
            System.out.println("商品信息更新成功！");
        } else {
            System.out.println("未找到指定ID的商品。");
        }
    }

    private void deleteProduct() {
        System.out.print("请输入要删除的商品ID: ");
        String id = scanner.nextLine();
        if (productDatabase.removeProductById(id)) {
            System.out.println("商品删除成功！");
        } else {
            System.out.println("未找到指定ID的商品。");
        }
    }

    private void viewAllOrders() {
        System.out.println("所有订单信息: ");
        for (Order order : productDatabase.getAllOrders()) {
            System.out.println(order);
        }
    }

    private void updateUser() {
        System.out.print("请输入要修改的用户名: ");
        String username = scanner.nextLine();
        User user = productDatabase.findUserByUsername(username);
        if (user != null) {
            System.out.print("请输入新的用户名(当前: " + user.getUsername() + "): ");
            String newUsername = scanner.nextLine();
            System.out.print("请输入新的密码(当前: " + user.getPassword() + "): ");
            String newPassword = scanner.nextLine();

            user.setUsername(newUsername);
            user.setPassword(newPassword);
            productDatabase.updateUser(user);
            System.out.println("用户信息更新成功！");
        } else {
            System.out.println("未找到指定用户名的用户。");
        }
    }

    private void queryProduct() {
        System.out.print("请输入商品名称: ");
        String productName = scanner.nextLine();
        Product product = productDatabase.findProductByName(productName);

        if (product != null) {
            System.out.println("商品名称: " + product.getName());
            System.out.println("商品价格: " + product.getPrice());
            System.out.println("商品库存: " + product.getStock());

            System.out.println("1. 购买商品");
            System.out.println("2. 返回用户菜单");
            System.out.print("请选择操作: ");
            int choice = scanner.nextInt();
            scanner.nextLine();  // 清除输入缓冲区中的换行符

            if (choice == 1) {
                purchaseProduct(product);
            }
        } else {
            System.out.println("未找到指定名称的商品。");
        }
    }

    private void purchaseProduct(Product product) {
        System.out.print("请输入购买数量: ");
        int quantity = scanner.nextInt();
        scanner.nextLine();  // 清除输入缓冲区中的换行符

        if (product.getStock() >= quantity) {
            double totalPrice = product.getPrice() * quantity;
            product.setStock(product.getStock() - quantity);

            OrderItem orderItem = new OrderItem(product, quantity, totalPrice);
            Order order = new Order(currentUser);
            order.addItem(orderItem);
            productDatabase.addOrder(order);

            System.out.println("购买成功！商品总价格: " + totalPrice);
        } else {
            System.out.println("库存不足，无法购买。");
        }
    }

    private void viewMyOrders() {
        System.out.println("我的订单信息: ");
        for (Order order : productDatabase.getOrdersByUser(currentUser)) {
            System.out.println(order);
        }

        System.out.println("1. 退款");
        System.out.println("2. 返回用户菜单");
        System.out.print("请选择操作: ");
        int choice = scanner.nextInt();
        scanner.nextLine();  // 清除输入缓冲区中的换行符

        if (choice == 1) {
            refundOrder();
        }
    }

    private void refundOrder() {
        System.out.print("请输入要退款的订单ID: ");
        String orderId = scanner.nextLine();

        List<Order> orders = productDatabase.getOrdersByUser(currentUser);
        Order refundOrder = null;

        for (Order order : orders) {
            if (order.getOrderId().equals(orderId)) {
                refundOrder = order;
                break;
            }
        }

        if (refundOrder != null) {
            productDatabase.getAllOrders().remove(refundOrder);
            System.out.println("订单退款成功！");
        } else {
            System.out.println("未找到指定ID的订单。");
        }
    }
}
